import React from 'react';
import {Avatar, Divider, Dropdown, Icon, Menu, Spin} from 'antd';
import moment from 'moment';
import Debounce from 'lodash-decorators/debounce';
import styles from '../GlobalHeader/index.less';
import ComponentBase from '../Base/ComponentBase';

export default class SelfServiceHeader extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {
      time: moment().format('YYYY-MM-DD HH:mm:ss'),
    };
  }

  componentDidMount() {
    this.timer = setInterval(this.getTime, 1000);
  }

  componentWillUnmount() {
    this.triggerResizeEvent.cancel();
    clearInterval(this.timer);
  }

  getTime = () => {
    const time = moment().format('YYYY-MM-DD HH:mm:ss');
    this.setState({time});
  };


  toggle = () => {
    const {collapsed, onCollapse} = this.props;
    onCollapse(!collapsed);
    this.triggerResizeEvent();
  };

  /* eslint-disable*/
  @Debounce(600)
  triggerResizeEvent() {
    const event = document.createEvent('HTMLEvents');
    event.initEvent('resize', true, false);
    window.dispatchEvent(event);
  }

  getUsername = user => {
    const name = user.nickname ? user.nickname : user.username;
    return name;
  };

  render() {
    const {
      onMenuClick,
    } = this.props;
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
        <Menu.Item disabled>
          <Icon type="user"/>个人中心
        </Menu.Item>
        <Menu.Item disabled>
          <Icon type="setting"/>设置
        </Menu.Item>
        <Menu.Divider/>
        <Menu.Item key="logout">
          <Icon type="logout"/>
          退出登录
        </Menu.Item>
      </Menu>
    );

    const userStr = localStorage.getItem('user');

    let user;
    try {
      user = JSON.parse(userStr);
    } catch {
      user = {'username': ''};
    }
    const time = this.state.time;
    const {relatingTenant = {}} = this.getLoginInfo();

    const {relatingTenantShortName, relatingTenantName} = relatingTenant;
    let shortName = relatingTenantShortName ? relatingTenantShortName : relatingTenantName;
    shortName += ' 自助订单系统';
    return (
      <div className={styles.right}>
        <Divider type="vertical"/>
        <span>{shortName}</span>
        <Divider type="vertical"/>
        {user.username ? (
          <Dropdown overlay={menu}>
              <span className={`${styles.action} ${styles.account}`}>
                <Avatar size="small" className={styles.avatar} icon={<Icon type="user"/>}/>
                <span>{this.getUsername(user)}</span>
              </span>
          </Dropdown>
        ) : (
          <Spin size="small" style={{marginLeft: 8}}/>
        )}

        <Divider type="vertical"/>
        <span>{time}</span>
      </div>
    );
  }
}
